import {
  drawerFormState,
  drawerTitle,
  drawerVisible,
  operateType,
  queryParams,
  resetFormState,
  searchList,
  tabPower,
  tableActiveKey,
  defaultTabsActiveKey,
  defaultSearchList,
  defaultTabsOptions,
} from "./store";
import styles from "./index.module.less";
import { searchConfig } from "./search";
import { tableData, tableConfig, tablePage, tableLoading } from "./table";
import { drawerConfig } from "./drawer";
import {
  fetchIncomeDetail,
  fetchIncomeSearchOptions,
  fetchPayDetail,
} from "./utils";
import { isHasPower } from "@/assets/directives/tools";
const showDrawer = () => (drawerVisible.value = true);
export const refreshTable = async (searchParams: any = {}) => {
  tablePage.current = 1;
  initObjAttr(queryParams, searchParams);
  await fetchList();
};
const handleFetchListTask = async (number) => {
  const defineApiMap = new Map([
    [0, () => tradeDetailApi.queryIncomeList(queryParams)],
    [1, () => tradeDetailApi.queryPayList(queryParams)],
  ]);
  let api: any = defineApiMap.get(number);
  const result: any = await api();
  if (result.code != 200) return message.error(result.message);
  tableData.value = result?.data?.order_list ?? [];
  tablePage.total = result?.data?.attributes?.total ?? 0;
};
export const fetchList = async () => {
  try {
    tableData.value.length = 0;
    tableLoading.value = true;
    queryParams.page = tablePage.current;
    queryParams.page_size = tablePage.pageSize;
    await handleFetchListTask(tableActiveKey.value);
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
const handleApiTask = async (string, number = 0, record) => {
  const defineApiMap = (string, number, record) => {
    const checkIncomeDetail = async () => {
      drawerTitle.value = $t("base.detail") + "-" + record.order_type;
      tableLoading.value = true;
      await fetchIncomeDetail(record);
      tableLoading.value = false;
      showDrawer();
    };
    const checkExpenditureDetail = async () => {
      drawerTitle.value = $t("base.detail") + "-" + record.order_type;
      drawerFormState.withdrawal_order_number = record.order_number;
      tableLoading.value = true;
      await fetchPayDetail(record);
      tableLoading.value = false;
      showDrawer();
    };
    const apiMap = new Map([
      [{ key: "view", state: 0 }, checkIncomeDetail],
      [{ key: "view", state: 1 }, checkExpenditureDetail],
    ]);
    return apiMap;
  };
  const apiMap: any = [...defineApiMap(string, number, record)].filter(
    ([object]) => object.key == string && object.state == number
  );
  apiMap.forEach(([, api]) => api.call(this));
};
export const handleAction = async ({ record, type }) => {
  operateType.value = type;
  resetFormState(drawerFormState);
  handleApiTask(operateType.value, tableActiveKey.value, record);
};
export default defineComponent({
  setup() {
    tabPower[0] = isHasPower("tradeDetailApi.queryIncomeList");
    tabPower[1] = isHasPower("tradeDetailApi.queryPayList");
    tableActiveKey.value = tabPower[0] ? 0 : tabPower[1] ? 1 : 0;
    searchList.value = defaultSearchList[tableActiveKey.value] ?? [];
    const defineSearch = searchConfig();
    const defineTable = tableConfig();
    const defineDrawer = drawerConfig();
    watch(
      () => sysZone.value,
      () => fetchList()
    );
    onActivated(() => {
      fetchIncomeSearchOptions();
      fetchList();
    });
    return () => (
      <>
        <s-search {...defineSearch} />
        <div class="mt16 mb8">
          {defaultTabsOptions[tableActiveKey.value].map(
            ({ label, value }: any, index: number) => {
              return (
                <s-button
                  class={[
                    styles["tabs-button"],
                    defaultTabsActiveKey[tableActiveKey.value] === index
                      ? styles.active
                      : "",
                  ]}
                  onClick={() => {
                    defaultTabsActiveKey[tableActiveKey.value] = value;
                    if (tableActiveKey.value === 0)
                      if (value === 0) queryParams.status = undefined;
                      else queryParams.status = value - 1;
                    else queryParams.status = value === 0 ? undefined : value;
                    refreshTable(deepClone(queryParams));
                  }}
                >
                  {label}
                </s-button>
              );
            }
          )}
        </div>
        <s-table {...defineTable} />
        <s-drawer {...defineDrawer} />
      </>
    );
  },
});
